import json, logging
from fastapi import Request, FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
import logging,json
import httpx
from pydantic import BaseModel
from typing import Optional, Generic, TypeVar
import httpx

from app.api import user,department
from app.db import redis

logging.basicConfig(level=logging.INFO)

class Player(BaseModel):
    age: int = 0
    name: str = ''

T = TypeVar('T', bound=BaseModel)  # 泛型类型，支持任意数据类型
class BaseResponse(BaseModel, Generic[T]):
    code: int = 0  # 默认成功
    msg: str = "OK"
    data: Optional[T] = None


app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return BaseResponse(
        code=400,
        msg=exc.errors()
    )

@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        content=BaseResponse(code=exc.status_code,msg=exc.detail).model_dump(),
        status_code=500,
        media_type="application/json"
    )


@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
    # TODO 使用异步日志库
    logging.error(f"Unexpected error: {exc}")
    return JSONResponse(
        content=BaseResponse(code=502, msg=str(exc)).model_dump(),
        status_code=502,
        media_type="application/json"
    )

@app.get("/")
async def root():
    try:
        async with httpx.AsyncClient() as client:
            r = await client.get("http://httpbin.org/anything/haha")
            r.raise_for_status()  # 自动检测 4xx/5xx 错误
            return r.json()
    except httpx.HTTPError as e:
        return {"error": f"HTTP Error: {str(e)}"}
    except json.JSONDecodeError:
        return {"error": "Invalid JSON response"}


@app.post("/qrLogin")
def qrLogin(request: Request):
    request.body()
    pass


@app.get("/items/{id}", response_model=BaseResponse[Player])
def get_item(id: str):
    return BaseResponse(data=Player(age=18,name='libz'))

@app.get("/httpbin")
async def http_client():
    async with httpx.AsyncClient() as client:
        try:
            rsp = await client.get("httpbin.org/anything/haha")
            rsp.raise_for_status()
            return rsp.json()
        except httpx.HTTPStatusError as e:
            print(f"HTTP error occurred: {e}")
        except httpx.RequestError as e:
            print(f"Request error occurred: {e}")
        except json.JSONDecodeError as e:
            print(f"decode json occurred: {e}")
        except Exception as e:
            print(f"{e}")
        

app.include_router(user.router)
app.include_router(department.router)

redis.init_redis()
